﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;

using SourceGrid;
using SourceGrid.Cells;
namespace iPdf
{
    /// <summary>
    /// The grid control with customized methods and fields, etc to fit our need for sessions management
    /// </summary>
    [System.ComponentModel.ToolboxItem(true)]
    partial class SessionsGrid : TataGridBase<TataSession>
    {
        #region Fields
        private string searchKeyword;

        private List<TataSession> sessionsList = new List<TataSession>();
        #endregion

        #region Properties

        #endregion

        #region Ctor
        public SessionsGrid()
        {
            InitializeControllersAndEditors();
        }
        #endregion

        #region Methods

        public void Load()
        {
            RowsCount = 1;
            FixedRows = 1;

            foreach (TataGridColumnInfo column in Columns)
            {
                CreateColumnHeader(column);
            }

            //make the Name column fixed
            Id.AutoSizeMode = SourceGrid.AutoSizeMode.None;
            SelectionMode = SourceGrid.GridSelectionMode.Row;
            Selection.EnableMultiSelection = true;
        }

        public void LoadSessions()
        {
            if (sessionsList.Count == 0)
            {
                FindSessions();
            }

            ShowSessions(sessionsList);
        }

        private void ShowSessions(List<TataSession> sessions)
        {
            //first, remove all items
            Redim(1, ColumnsCount);

            foreach (TataSession session in sessions)
            {
                if (session.Page == Global.CurrentPage)
                {
                    AddSessionRow(session);
                }
            }

            ColumnHeader sessionNameColHeader = (ColumnHeader)Id[0];

            if (sessionNameColHeader.SortComparer == null)
            {
                sessionNameColHeader.SortComparer = SessionOperationToolStrip.DefaultComparer;
            }
            sessionNameColHeader.Sort(true);
        }

        public void FindSessions()
        {
            string dir = TataSession.SessionsDir;
            int upLimit = TataSession.MaxSessionsCount;
            FileInfo[] foundFiles = Helper.FindFilesInDirectory
                                (dir, TataSession.SessionFormat);
            Array.Sort(foundFiles, new FileInfoComparer());

            int count = 0;
            foreach (FileInfo file in foundFiles)
            {
                ++count;
                if (count <= upLimit)
                {
                    TataSession session = new TataSession();
                    session.FileName = file.FullName;
                    sessionsList.Add(session);
                }
                else
                {
                    Helper.DeleteFile(file.FullName);
                }
            }
        }

        public void AddSession(TataSession session)
        {
            if (this.sessionsList.Count > 0)
            {
                this.sessionsList.Add(session);
            }
        }

        protected void AddSessionRow(TataSession session)
        {
            int row = RowsCount;
            Rows.Insert(row);
            Rows[row].Height = gridRowHeight;

            foreach (TataGridColumnInfo colInfo in Columns)
            {
                colInfo.Create(session);
            }
        }

        protected SourceGrid.Cells.Cell CreateSessionCell(
                                    TataSession session, string text,
                                    string toolTipText,
                                    SourceGrid.Cells.Editors.EditorBase editor)
        {
            SourceGrid.Cells.Cell cell = new SourceGrid.Cells.Cell(text);
            cell.View.Font = gridFont;
            cell.Tag = session;

            cell.ToolTipText = toolTipText;
           
            cell.AddController(committingController);
            cell.AddController(toolTip);
            cell.AddController(hoverPreviewController);
            cell.AddController(keyController);

            cell.Editor = editor;
            return cell;
        }

        protected SourceGrid.Cells.Cell CreateSessionNameCell(TataSession session)
        {
            return CreateSessionCell(session, session.Name,
                session.Name, nameCellEditor);
        }

        protected void CreateIDColumn(TataSession session)
        {
            Id[RowsCount-1] = CreateSessionNameCell(session);
        }

        protected SourceGrid.Cells.Cell CreateSessionDescriptionCell(TataSession session)
        {
            string toolTipText = string.IsNullOrEmpty(session.Description) ?
                        global::iPdf.Properties.Resources.EmptyCellTip : session.Description ;
            
            return CreateSessionCell(session, session.Description, 
                toolTipText, descriptionCellEditor);
        }

        protected void CreateInfoColumn(TataSession session)
        {
            Info[RowsCount - 1] = CreateSessionDescriptionCell(session);
        }

        protected TataSession ExtractSessionAtRow(int rowIndex)
        {
            if (rowIndex < 1 || rowIndex >= RowsCount)
            {
                return null;
            }

            SourceGrid.Cells.Cell cell = Id[rowIndex];
            return (TataSession)cell.Tag;
        }

        protected void RemoveRow(int rowIndex)
        {
            TataSession session = ExtractSessionAtRow(rowIndex);
            session.Delete();
            sessionsList.Remove(session);
            this.Rows.Remove(rowIndex);
        }

        protected void CommitImporting(TataSession session)
        {
            if (session.ImportingEnabled)
            {
                session.Import();
                Global.CurrentPage.StartAction();
            }
        }

        private bool MatchSession(TataSession session)
        {
            if (string.IsNullOrEmpty(searchKeyword))
            {
                return true;
            }

            return session.Name.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) != -1 ||
                        session.Description.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) != -1;
        }

        public void Search(string keyword)
        {
            searchKeyword = keyword;
            List<TataSession> searchResult = this.sessionsList.FindAll(MatchSession);

            ShowSessions(searchResult);
        }

        #endregion
    }
}
